class Solution {
public:
    int m, n;
    bool vis[500][500];
    int numEnclaves(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < n;j++)
            {
                if ((i == 0 || j == 0 || i == m - 1 || j == n - 1) && grid[i][j] == 1)
                {
                    bfs(grid, i, j);
                }
            }
        }
        int sum = 0;
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < n;j++)
            {
                if (vis[i][j] == false && grid[i][j] == 1)
                {
                    sum++;
                }
            }
        }
        return sum;

    }
    int dx[4] = { -1,1,0,0 };
    int dy[4] = { 0,0,-1,1 };
    void bfs(vector<vector<int>>& grid, int i, int j)
    {
        queue<pair<int, int>> q;
        vis[i][j] = true;q.push({ i,j });
        while (q.size())
        {
            auto [a, b] = q.front();q.pop();
            for (int k = 0;k < 4;k++)
            {
                int x = a + dx[k], y = b + dy[k];
                if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 && vis[x][y] == false)
                {
                    vis[x][y] = true;q.push({ x,y });
                }
            }
        }
    }
};